(function() {
    'use strict';

    angular
        .module('milkbeeApp')
        .controller('MyAddressDialogController', MyAddressDialogController);

    MyAddressDialogController.$inject = ['$timeout', '$scope','$http', '$stateParams', '$uibModalInstance', 'entity', 'MyAddress'];

    function MyAddressDialogController ($timeout, $scope, $http,$stateParams, $uibModalInstance, entity, MyAddress) {
        var vm = this;

        vm.address = entity;
        vm.clear = clear;
        vm.datePickerOpenStatus = {};
        vm.openCalendar = openCalendar;
        vm.save = save;

        $timeout(function (){
            angular.element('.form-group:eq(1)>input').focus();
        });

        function clear () {
            $uibModalInstance.dismiss('cancel');
        }

        function save () {
            vm.isSaving = true;
            if (vm.address.id !== null) {
            	MyAddress.update(vm.address, onSaveSuccess, onSaveError);
            } else {
            	MyAddress.save(vm.address, onSaveSuccess, onSaveError);
            }
        }

        function onSaveSuccess (result) {
            $scope.$emit('milkbeeApp:myAddressUpdate', result);
            $uibModalInstance.close(result);
            vm.isSaving = false;
        }

        function onSaveError () {
            vm.isSaving = false;
        }

        vm.datePickerOpenStatus.createdAt = false;
        vm.datePickerOpenStatus.modifiedAt = false;

        function openCalendar (date) {
            vm.datePickerOpenStatus[date] = true;
        }
        //////////////////////////////////////////////////
        function loadProvinces(){
        	$http({
        		method: 'get',
        		url: '/api/pub/areas/provinces',
        		transformRequest: angular.identity
        	}).success(function(ret){
        		vm.provinces=ret;
        	});
        }
        vm.provinceChange= function loadCities(province){
        	$http({
        		method: 'get',
        		url: '/api/pub/areas/cities/'+province,
        		transformRequest: angular.identity
        	}).success(function(ret){
        		vm.cities=ret;
        	});
        	vm.address.province=vm.province.name;
        }
        vm.cityChange= function loadCounties(city){
        	$http({
        		method: 'get',
        		url: '/api/pub/areas/counties/'+city,
        		transformRequest: angular.identity
        	}).success(function(ret){
        		vm.counties=ret;
        	});
        	vm.address.city=vm.city.name;
        }
        vm.countyChange=function onCountyChange(county){
        	vm.address.county=vm.county.name;
        }     
        
        loadProvinces();
        
    }
})();
